package ibm.websphere.monitor.util;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.sql.Date;
import java.sql.ResultSet;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;
import java.util.Set;

import ibm.websphere.monitor.bean.JvmInfo;
import ibm.websphere.monitor.bean.MenuInfo;
import ibm.websphere.monitor.bean.UserInfo;
import org.apache.log4j.Logger;

import javax.sound.midi.Sequence;


/**
 * <pre>
 *  LBS日志投诉处理业务平台的公共方法
 * </pre>
 * @author ZHOU YANG
 * @version 1.0
 */
public class UtilTool {

    private static Logger logger = Logger.getLogger(UtilTool.class);


    /**
     * <pre>
     * 	初始化登陆出错码
     * </pre>
     *
     * @return
     */
    public static Map<String, String> init() {
        Map<String, String> errorCode = new HashMap<String, String>();
        errorCode.put("0", "该用户不存在，请重试。");
        errorCode.put("1", "密码错误，请确认后重试。");
        errorCode.put("2", "该用户没有被激活。");
        errorCode.put("3", "验证码错误，请重新输入。");
        errorCode.put("4", "请输入用户名。");
        return errorCode;
    }

    /**
     * <pre>
     * 	根据错误码返回错误信息
     * </pre>
     *
     * @param key
     * @return
     */
    public static String getErrorCode(String key) {
        return init().get(key);
    }


    /**
     * <pre>
     * 	初始化加载的菜单信息
     * </pre>
     * @param menuInfoList
     * @param menuSet
     * @param contextPath
     * @return
     */
    public static final String dump(List<MenuInfo> menuInfoList,List<MenuInfo> menuSet,String contextPath) {

        StringBuffer buf = new StringBuffer("var root = new TreeView('root', '', '');\r\n");

        buf.append("root.add(0, -1, '主机列表导航', '', '', '_top', '', '主机列表导航', Icon.open.src);\r\n");

        for(MenuInfo menu : menuInfoList){
            //menu.getTranslate();
            buf.append(add(menu.getMenuId(), menu.getMenuPid(), menu.getMenuName(), ""));

            for(MenuInfo d : menuSet){
                //d.getTranslate();
                if(menu.getMenuId().equals(d.getMenuPid())){
                    buf.append(add(d.getMenuId(), d.getMenuPid(), d.getMenuName(),  contextPath+Constants.WAS_MENU_URL+d.getMenuName()+"&type="+d.getMenuType()));
                }
            }

        }

        buf.append("document.write(root);\r\n");

		logger.info("【菜单生成】【生成菜单如下：" + buf.toString() + "】");

        return buf.toString();
    }


    /**
     * <pre>
     * 	增加菜单信息
     * </pre>
     *
     * @param id
     * @param parentId
     * @param title
     * @param url
     * @return
     */
    public static String add(Long id, Long parentId, String title, String url) {
        return "root.add(" + id + ", " + parentId + ", '" + title + "', '" + url + "', '1', 'mainFrm', '" +
                ((parentId == 0) ? "quickmenuFrm" : "") + "', '" + title + "', " +
                ((parentId == 0) ? "''" : "Icon.receive.src") + ");\r\n";
    }

    public static String addTree(String id, String parentId, String title, String url) {
        System.out.println(parentId + "***");
        return "root.add('" + id + "', '" + parentId + "', '" + title + "', '" + url + "', '1', 'deptFrm', '" +
                ((parentId.equals("1")) ? "quickmenuFrm" : "") + "', '" + title + "', " +
                ((parentId.equals("1")) ? "''" : "Icon.receive.src") + ");\r\n";
    }


    /**
     * <pre>
     * 	根据分割符，返回一个字符串数组
     * </pre>
     *
     * @param comminute 分割符号
     * @return
     */
    public static String[] getArrayComminute(String content, String comminute) {
        return content.split(comminute);
    }

    /**
     * <pre>
     * 并将值从ISO-8859-1转为UTF-8编码
     * </pre>
     *
     * @param key
     * @return
     */
    public static String toUTF(String key) {
        return iconv(key, "ISO-8859-1", "utf-8");
    }

    /**
     * <pre>
     * 并将值从ISO-8859-1转为UTF-8编码
     * </pre>
     *
     * @param key
     * @return
     */
    public static String toGBK(String key) {
        return iconv(key, "ISO-8859-1", "GBK");
    }

    public static String iconv(String source, String from, String to) {
        if (source != null) {
            try {
                return new String(source.getBytes(from), to);
            } catch (Exception ex) {
                return source;
            }
        }
        return source;
    }




    /**
     * 检查字符串是否为空
     *
     * @param value
     * @return
     */
    public static boolean checkStringValueExist(String value) {
        if (value == null || "".equals(value.trim()))
            return false;
        return true;
    }

    /**
     * 检查两个字符串是否都为空
     *
     * @param value
     * @param value2
     * @return
     */
    public static boolean checkStringValueExist(String value, String value2) {
        boolean flag = true;
        if (value == null || "".equals(value.trim())) {
            flag = false;
        }
        if (value2 == null || "".equals(value2.trim())) {
            flag = false;
        }
        return flag;
    }

    /**
     * <pre>
     * 	判读该目录下是否有文件
     * </pre>
     *
     * @param file
     * @return
     */
    public static boolean checkFile(File file) {
        if (file.isDirectory()) {
            if (file.listFiles().length > 0) {
                return true;
            } else {
                return false;
            }
        } else {
            return false;
        }
    }

    /**
     * <pre>
     * 	判读该目录下文件名是否重复
     * </pre>
     *
     * @param file
     * @return
     */
    public static boolean checkFileName(File file, String name) {
        if (file.isDirectory()) {
            File f[] = file.listFiles();
            for (File fi : f) {
                if (fi.getName().equals(name)) {
                    return true;
                }
            }
        } else {
            return false;
        }
        return true;
    }

    /**
     * <pre>
     * 	判断LIST对象是否为空
     * </pre>
     *
     * @param obs
     * @return
     */
    public static boolean checkListValueExist(List obs) {
        if (obs == null || obs.size() == 0)
            return false;
        return true;
    }

    /**
     * <pre>
     * 	判断LIST对象是否为空
     * </pre>
     *
     * @param obs
     * @return
     */
    public static boolean checkObjectValueExist(Object obs) {
        if (obs == null)
            return false;
        return true;
    }

    /**
     * <pre>
     * 	把OBJECT类型转换成LONG类型
     * </pre>
     *
     * @param obj
     * @return
     */
    public static Long objectConvLong(Object obj) {
        return Long.parseLong(obj.toString());
    }

    /**
     * <pre>
     * 	把OBJECT类型转换成Date类型
     * </pre>
     *
     * @param obj
     * @return
     */
    public static Date objectConvDate(Object obj) {
        return Date.valueOf(obj.toString());
    }

    /**
     * <pre>
     *  根据传过来的数组，进行分组
     * </pre>
     *
     * @param content
     * @return
     */
    public static List<List<String>> dumpList(String[] content) {
        String titleCount = content[0];
        String key = keyIndex(titleCount);
        List<String> arrayString = new ArrayList<String>();
        List<List<String>> resultList = new ArrayList<List<String>>();
        for (String value : content) {
            String contentVlaue = keyIndex(value);
            if (key.equals(contentVlaue)) {
                arrayString.add(value);
            } else {
                resultList.add(arrayString);
                arrayString = new ArrayList<String>();
                arrayString.add(value);
                key = keyIndex(value);
            }
        }
        resultList.add(arrayString);
        return resultList;
    }

    /**
     * <pre>
     * 	根据CONTENT返回第二位的数值
     *  EG:1|4|3|2  返回4
     * </pre>
     *
     * @param content
     * @return
     */
    public static String keyIndex(String content) {
        if (checkStringValueExist(content)) {
            return content.substring(content.indexOf("|") + 1, content.indexOf("|", content.indexOf("|") + 1));
        } else {
            return "";
        }
    }


//    public static String getJSON(List<LbsLogFlowinfo> flowInfo){
//    	StringBuffer buffer = new StringBuffer();
//    	buffer.append("[ ");
//    	for(LbsLogFlowinfo info : flowInfo){
//    		buffer.append("{id:").append("'"+info.getId()+"'").append(",");
//    		buffer.append("MESSAGETYPE:").append("'"+info.getMessagetype()+"'").append(",");
//    		buffer.append("REQUESTOR:").append("'"+info.getRequestor()+"'");
//    		buffer.append("}");
//    	}
//    	buffer.append("]");
//    	System.out.println(buffer.toString());
//    	return buffer.toString();
//    }

    /**
     * 判断流程走向 -1全部 0 LE接口 1 LR接口
     *
     * @param flowCode
     * @return
     */
    public static String getFlow(String flowCode) {
        String flow = "全部";
        if (flowCode == "1") {
            flow = "LR接口";
        } else if (flowCode == "0") {
            flow = "LE接口";
        }
        return flow;
    }

    /**
     * 判断流程走向 -1全部 0 LE接口 1 LR接口
     *
     * @param flowCode
     * @return
     */
    public static String getAllRecord(String flowCode) {
        String flow = "全部记录";
        if (flowCode == "1") {
            flow = "失败记录";
        } else if (flowCode == "0") {
            flow = "成功记录";
        }
        return flow;
    }

    /**
     * 方法名称：getSortedHashtable
     * 参数：Hashtable h 引入被处理的散列表
     * 描述：将引入的hashtable.entrySet进行排序，并返回
     */
    @SuppressWarnings("unchecked")
    public static Map.Entry[] getSortedHashtableByKey(Hashtable hashtable) {

        Set set = hashtable.entrySet();

        Map.Entry[] entries = (Map.Entry[]) set.toArray(new Map.Entry[set.size()]);

        Arrays.sort(entries, new Comparator() {
            public int compare(Object arg0, Object arg1) {
                Object key1 = ((Map.Entry) arg0).getKey();
                Object key2 = ((Map.Entry) arg1).getKey();
                return ((Comparable) key1).compareTo(key2);
            }

        });

        return entries;
    }

    public static String getSeque() {
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss S");// 设置日期格式
        String nowTime = df.format(new java.util.Date()).replace("-", "")
                .replace(":", "").replace(" ", "");
        return nowTime;
    }


    public List makeObjectList(Object clazz,ResultSet rs ){
        try {
            if (clazz instanceof JvmInfo) {
                Class obj = Class.forName("JvmInfo");
                Field [] field = obj.getFields();
                for (Field f : field){
                    System.out.println(f.getName());
                }
            } else {

            }
        }catch (Exception ex){
            ex.printStackTrace();
        }
        return null;
    }



    public static void main(String args[]) throws Exception {
//
//        String url = "id_|receiver_1|consignor_|address_全部|begin_2013-09-11|end_2013-09-24";


//        Class obj = Class.forName("ibm.websphere.monitor.bean.JvmInfo");
//        Field [] field = obj.getFields();
//        for (Field f : field){
//            System.out.println(f.getName());
//        }


//        Class<?> clz = UserInfo.class.getClass();
//        Constructor<?> cons[] = clz.getConstructors();

        String dd = "dfdcde.";
        System.out.println(dd.substring(0,dd.length()-1));
    }
}
